package com.open.basic.thread;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author system
 * @Date 2024/1/22 16:19
 * @description 系统默认线程工厂
 */
public class SystemThreadFactory implements ThreadFactory {

    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    // 线程计数器
    private final AtomicInteger threadCounter = new AtomicInteger(1);

    private ThreadGroup threadGroup = null;
    // 线程前缀名
    private final String namePrefix;
    // 是否为守护线程
    private final boolean daemon;

    public SystemThreadFactory(String name) {
        this(name, false);
    }

    public SystemThreadFactory(String name, boolean daemon) {
        threadGroup = Thread.currentThread().getThreadGroup();
        if (name == null || name.isEmpty()) {
            name = "pool";
        }
        // if (name.lastIndexOf("-") == name.length() - 1) {
        //     this.namePrefix = name;
        // } else {
        //     this.namePrefix = name;
        // }
        this.namePrefix = name;
        this.daemon = daemon;
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(threadGroup, r, namePrefix + "-" + threadCounter.getAndIncrement(), 0);
        t.setName(namePrefix + "-thread-" + threadCounter.incrementAndGet());
        t.setDaemon(daemon);
        return t;
    }
}
